package repositories

import (
	"fmt"
	"myapi/internal/models"

	"gorm.io/gorm"
)

type ArticleRepository struct {
	db *gorm.DB
}

func NewArticleRepository(db *gorm.DB) *ArticleRepository {
	return &ArticleRepository{db: db}
}

// Create 文章创建
func (r *ArticleRepository) Create(article *models.Article) error {
	return r.db.Create(article).Error
}

// GetAll 文章列表
func (r *ArticleRepository) GetAll(page, pageSize int) ([]*models.Article, error) {
	var articles []*models.Article
	err := r.db.Order("created_at desc").
		Limit(pageSize).
		Offset((page - 1) * pageSize).
		Find(&articles).Error
	if err != nil {
		return nil, err
	}
	return articles, nil
}

// Detail 文章详情
func (r *ArticleRepository) Detail(id uint) (*models.Article, error) {
	var article models.Article
	if err := r.db.First(&article, id).Error; err != nil {
		return nil, err
	}
	fmt.Println(&article)
	return &article, nil
}

// Delete 删除文章
func (r *ArticleRepository) Delete(id uint) error {
	return r.db.Delete(&models.Article{}, id).Error
}

// Update 修改文章
func (r *ArticleRepository) Update(article *models.Article) error {
	return r.db.Save(article).Error
}
